#ifndef QTLOGGER_H
#define QTLOGGER_H

#include <QThread>
#include <QVector>
#include <QString>
#include <QTextStream>
#include <QFile>
#include <QDebug>
#include <QDateTime>
#include <QObject>
#include <QMutex>

static QVector<QString> logQueue;
static QMutex mutex;

class QtLogger :public QThread
{

public:
    QtLogger();

    static void WriteLog(QString logMsg);
    void run();
    void stop();

    ~QtLogger();

private:
    QString logFileDir;
    QString logFileName;
    QString logFilePath;
    QTextStream *logStream;
    QFile *logFile;
    volatile bool stopped;
};

#define WRITE_LOG(type, msg)(\
{\
    QString logType;\
    switch(type){\
        case QtDebugMsg:{logType = "[D]";}break;\
        case QtWarningMsg:{logType = "[W]";}break;\
        case QtCriticalMsg:{logType = "[C]";}break;\
        case QtFatalMsg:{logType = "[F]";}break;\
        default:{logType = "[I]";}break;}\
    QDateTime DT = QDateTime::currentDateTime();\
    QString DTStr = QString("[%1]").arg(DT.toString("yyyy-MM-dd hh:mm:ss"));\
    QString File = QString("[file:%1]").arg(__FILE__);\
    QString FuncStr = QString("[function:%1]").arg(__FUNCTION__);\
    QString Line = QString("[line:%1]").arg(__LINE__);\
    QString logMsg = QString("%1 %2 %3 %4 %5 %6").arg(DTStr).arg(logType).arg(File).arg(FuncStr).arg(Line).arg(msg);\
    qDebug("%s", logMsg.toLocal8Bit().data());\
    QtLogger::WriteLog(logMsg);\
})

#define LOGI(msg)(WRITE_LOG(QtInfoMsg,msg))
#define LOGD(msg)(WRITE_LOG(QtDebugMsg,msg))
#define LOGW(msg)(WRITE_LOG(QtWarningMsg,msg))
#define LOGC(msg)(WRITE_LOG(QtCriticalMsg,msg))
#define LOGF(msg)(WRITE_LOG(QtFatalMsg,msg))

#endif // QTLOGGER_H
